package java_thinking.unit_17._17_2_6;

import java.util.*;

/**
 * @Desc:   修改CountingMapData 通过添加像Countries.java那样定制EntrySet类，来完全实现享元
 * @author: cww
 * @DateTime: 2019/4/15 8:54
 */
class CountingMapData2 extends AbstractMap<Integer,String> {
    private static String[] countries = "A B".split(" ");

    private int size;

    public CountingMapData2(int size) {
        this.size = size < 0 ? 0 : size;
    }

    //1.返回Set对象的方法
    @Override
    public Set<Map.Entry<Integer, String>> entrySet() {
        return countrySet;
    }

    private Set<Map.Entry<Integer,String>> countrySet = new EntrySet();

    private class EntrySet extends AbstractSet<Map.Entry<Integer,String>> {

        @Override
        public Iterator<Map.Entry<Integer, String>> iterator() {
            return new Iter();
        }

        @Override
        public int size() {
            return size;
        }
    }

    private class Iter implements Iterator<Map.Entry<Integer, String>> {

        private Entry entry = new Entry(-1);
        @Override
        public boolean hasNext() {
            return entry.index < size -1;
        }

        @Override
        public Map.Entry<Integer, String> next() {
            entry.index++;
            return entry;
        }
    }

    private class Entry implements Map.Entry<Integer,String> {

        int index;

        public Entry(int index) {
            this.index = index;
        }

        @Override
        public Integer getKey() {
            return index;
        }

        @Override
        public String getValue() {
            return countries[ index % countries.length]+Integer.toString(index/countries.length);
        }

        @Override
        public String setValue(String value) {
            throw new UnsupportedOperationException();
        }

        @Override
        public int hashCode() {
            return Integer.valueOf(index).hashCode();
        }

        @Override
        public boolean equals(Object obj) {
            return obj instanceof Entry && index == ((Entry)obj).index;
        }
    }


}
public class E05_CountingMapData2 {
    public static void main(String[] args) {
        CountingMapData2 data2 = new CountingMapData2(60);
        for (Map.Entry<Integer,String> entry : data2.entrySet()){
            System.out.print(entry.getKey() + "=" + entry.getValue()+" ");
        }
        System.out.println();
        System.out.println(data2);

    }
}
